<?php

namespace Modules\Groupon\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Groupon\Entities\Groupon;

use Validator;
use ThrowException;
use Auth;
use DB;

class GrouponController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $options = $req->all();

        $options['with'] = ['product'];

        $list = Groupon::getList($options);

        return $list->generateListResponse();
    }

    public function store(Request $req)
    {
        $rule = [
            'product' => ['required', 'array'],
            'product.skus' => ['required', 'array'],
            'type' => ['required'],
            'timeout' => ['required'],
            'start_at' => ['required'],
            'end_at' => ['required'],
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        DB::beginTransaction();

        $item = Groupon::createWithReq($req);

        DB::commit();

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function show(Request $req, $uuid)
    {
        $groupon = Groupon::getEntity([
            'uuid' => $uuid,
            'with' => ['skus']
        ]);

        $info = $groupon->getInfo();

        return [
            'info' => $info
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
            'type' => 'required',
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $item = Groupon::getEntity([
            'uuid' => $uuid
        ]);

        if ($req->type === 'update')
            $item->updateWith($req->input('attributes'));
        elseif ($req->type === 'close')
            $item->close(1);

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $item = Groupon::getEntity([
            'uuid' => $uuid
        ]);

        if ($item->status !== 2)
            ThrowException::Conflict('请先关闭活动，不关闭活动不可删除');

        $item->delete();

        return [];
    }
}
